package com.mvc.business.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvc.ProjectUtils;
import com.mvc.business.model.PurchaseItem;
import com.mvc.business.model.Schedule;
import com.mvc.business.service.PurchaseItemManager;
import com.mvc.framework.service.PageManager;
import com.mvc.framework.util.AjaxUtils;
import com.mvc.framework.util.DoubleUtils;
import com.mvc.framework.web.BaseController;

/**
 * 
 * @author Bob pu [bangxiong.pu@covidien.com]
 * @version V1.0 Create Time: 2012-9-1
 */
@Controller
@RequestMapping("purchaseItem")
public class PurchaseItemController extends BaseController<PurchaseItem> {
	private static final Logger	LOGGER	= Logger.getLogger(PurchaseItemController.class);

	@Autowired
	private PurchaseItemManager	purchaseItemManager;

	@RequestMapping("list/{purchaseId}")
	public String list(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer purchaseId) throws Exception {
		List<PurchaseItem> orderItems = purchaseItemManager.getPurchaseItemsByPurchaseId(purchaseId);
		int total = orderItems.size();
		StringBuilder rows = new StringBuilder(total);
		rows.append("{");
		rows.append("\"total\":\"").append(1);
		rows.append("\",\"page\":\"").append(1);
		rows.append("\",\"records\":\"").append(total);
		rows.append("\",\"rows\":[");
		for (int i = 0; i < total; i++) {
			PurchaseItem orderItem = orderItems.get(i);
			rows.append(getPurchaseItemJson(orderItem));
			if (i != total - 1) {
				rows.append(",");
			}
		}
		rows.append("]");
		rows.append("}");
		AjaxUtils.doJsonResponse(response, rows.toString());
		return null;
	}

	private String getPurchaseItemJson(PurchaseItem orderItem) {
		StringBuilder row = new StringBuilder(80);
		row.append("{\"id\":\"").append(orderItem.getId());
		row.append("\",\"cell\":[\"").append(orderItem.getId());
		row.append("\",\"").append(orderItem.getObjectId());
		row.append("\",\"").append(ProjectUtils.toJsonField(orderItem.getCustomerPurchaseNo()));
		row.append("\",\"").append(ProjectUtils.toJsonField(orderItem.getEnglishName()));
		row.append("\",\"").append(ProjectUtils.toJsonField(orderItem.getName()));
		row.append("\",\"").append(orderItem.getQuantity());
		row.append("\",\"").append(orderItem.getUnit());
		row.append("\",\"").append(orderItem.getUnitPrice());
		row.append("\",\"").append(DoubleUtils.toFixFraction(orderItem.getUnitPrice() * orderItem.getQuantity(), 3));
		row.append("\"]}");
		return ProjectUtils.replaceReturn(row.toString());
	}

	@RequestMapping("save")
	public String save(HttpServletRequest request, PurchaseItem orderItem, ModelMap modelMap) throws Exception {
		String operation = request.getParameter("oper");
		boolean result = false;
		try {
			if (operation.equals("del")) {
				int id = Integer.parseInt(request.getParameter("id"));
				purchaseItemManager.delete(id);
			} else if (operation.equals("add")) {
				orderItem.setId(null);
				purchaseItemManager.save(orderItem);
			} else if (operation.equals("edit")) {
				purchaseItemManager.save(orderItem);
			}
			result = true;
		} catch (Exception e) {
			LOGGER.error("save", e);
		}
		modelMap.addAttribute("status", result ? "success" : "error");
		return "jsonView";
	}

	@RequestMapping("importToSchedule")
	public String importToPacking(String purchaseIds, Schedule example, ModelMap modelMap) {
		int count = 0;
		if (StringUtils.isNotBlank(purchaseIds)) {
			List<Integer> ids = new ArrayList<Integer>();
			for (String id : purchaseIds.split(",")) {
				try {
					ids.add(Integer.parseInt(id));
				} catch (Exception e) {
				}
			}
			count = purchaseItemManager.importToSchedule(ids.toArray(new Integer[0]), example);
		}
		example.setObjectId(-1);
		example.setPurchaseId(-1);
		example.setSupplierId(-1);
		modelMap.addAttribute("result", count);
		return "jsonView";
	}

	@RequestMapping("importToBankStatement/{bankStatementId}")
	public String importToBankStatement(String purchaseIds, @PathVariable Integer bankStatementId, ModelMap modelMap) {
		int count = 0;
		if (StringUtils.isNotBlank(purchaseIds)) {
			List<Integer> ids = new ArrayList<Integer>();
			for (String id : purchaseIds.split(",")) {
				try {
					ids.add(Integer.parseInt(id));
				} catch (Exception e) {
				}
			}
			count = purchaseItemManager.importToBankStatement(ids.toArray(new Integer[0]), bankStatementId);
		}
		modelMap.addAttribute("result", count);
		return "jsonView";
	}

	@Override
	public PageManager<PurchaseItem> getEntityManager() {
		return purchaseItemManager;
	}

	@Override
	public String getFileBasePath() {
		return null;
	}

}
